package com.lc.mqtt.config;

import com.lc.mqtt.properties.MqttProperties;
import com.study.common.constant.MqttConstant;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @description: some desc
 * @author: LChuang
 * @date: 2023/11/13 10:47
 */
@Slf4j
@Configuration
public class MqttClientConfig {

    @Autowired
    private MqttProperties mqttProperties;

    @Bean
    public MqttClient getMqttClient() {
        MemoryPersistence persistence = new MemoryPersistence();
        MqttClient mqttClient = null;
        try {
            // 初始化mqtt服务器
            mqttClient = new MqttClient(mqttProperties.getHost(), mqttProperties.getClientId(), persistence);
            log.info("初始化mqtt服务：{}", mqttProperties.getHost());
            // mqtt 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setAutomaticReconnect(true);
            connOpts.setUserName(mqttProperties.getUsername());
            connOpts.setPassword(mqttProperties.getPassword().toCharArray());
            // mqtt 会话保存
            connOpts.setCleanSession(true);
            // 设置回调
            mqttClient.setCallback(new MyMqttCallback(mqttClient, connOpts, mqttProperties.getClientId()));
            // 建立连接
            log.info("连接mqtt服务：{}", mqttProperties.getClientId());
            mqttClient.connect(connOpts);
            // 设置订阅
            if (mqttProperties.getClientId().equals(MqttConstant.LOCAL_MQTT_CLIENT)) {
                mqttClient.subscribe(MqttTopic.Topics);
                log.info("{}服务器订阅主题：{}", mqttClient.getClientId(), MqttTopic.Topics);
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
        return mqttClient;
    }

}
